﻿
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace wpf.Triage.Convert
{
    public class DateTimeConvert : IValueConverter
    {
        /// <summary>
        /// 字符串转时间  2022-03-28
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            object Defult =null;
            if (parameter!=null)
            {//设置默认值为null，还是当前时间
                if (parameter.ToString().Equals("Now"))
                {
                    Defult = DateTime.Now;
                }
            }
            if (value == null)
            {
                return Defult;
            }
            else
            {
                try
                {
                    DateTime dt = System.Convert.ToDateTime(value);
                    return dt;
                }
                catch (Exception e)
                {
                    return Defult;
                }
            }
        }
        /// <summary>
        /// 时间转通用格式字符串  2022-03-28
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string res = null;
            if (value != null)
            {
                try
                {
                    res = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
                }
                catch (Exception e)
                {
                    res = string.Empty;
                }
            }
            return res;
        }
    }
}
